package com.example.demo.service.impl;

import com.example.demo.entity.QRole;
import com.example.demo.entity.QUser;
import com.example.demo.entity.User;
import com.example.demo.entity.vo.UserVO;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.IUserService;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    private final QUser qUser = QUser.user;
    private final QRole qRole = QRole.role;


    @Override
    public User findUserByUsername(String username) {
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUser.username.eq(username));
        return jpaQueryFactory.selectFrom(qUser).where(builder).fetchOne();
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public UserVO findUserWithRoleByUserId(Long userid) {
        return jpaQueryFactory.select(Projections.bean(UserVO.class, qUser.username, qUser.userAge, qRole.roleName))
                .from(qUser)
                .leftJoin(qRole)
                .on(qUser.roleId.eq(qRole.roleId))
                .where(qUser.userId.eq(userid))
                .fetchOne();
    }
}
